package com.chatplus.application.controller.admin.biz;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.domain.entity.basedata.ApiKeyEntity;
import com.chatplus.application.domain.entity.chat.ChatModelEntity;
import com.chatplus.application.domain.request.ChatModelSaveRequest;
import com.chatplus.application.domain.request.FiledUpdateRequest;
import com.chatplus.application.domain.response.ChatModelDetailResponse;
import com.chatplus.application.service.basedata.ApiKeyService;
import com.chatplus.application.service.chat.ChatModelService;
import com.chatplus.application.web.basecontroller.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/admin/model")
@Tag(name = "后台操作模型 API", description = "后台操作模型 API")
public class ChatModelAdminApiController extends BaseController {
    private final ChatModelService chatModelService;
    private final ApiKeyService apiKeyService;


    public ChatModelAdminApiController(ChatModelService chatModelService,
                                       ApiKeyService apiKeyService) {
        this.chatModelService = chatModelService;
        this.apiKeyService = apiKeyService;
    }

    @GetMapping("/list")
    @Operation(summary = "后台获取模型列表")
    public List<ChatModelDetailResponse> list() {
        List<ChatModelEntity> list = chatModelService.list(new LambdaQueryWrapper<ChatModelEntity>()
                .orderByAsc(ChatModelEntity::getSortNum));
        List<ChatModelDetailResponse> responseList = new ArrayList<>();
        for (ChatModelEntity entity : list) {
            ChatModelDetailResponse response = BeanUtil.copyProperties(entity, ChatModelDetailResponse.class, "createdAt", "updatedAt");
            response.setCreatedAt(entity.getCreatedAt().getEpochSecond());
            response.setUpdatedAt(entity.getUpdatedAt().getEpochSecond());
            responseList.add(response);
        }
        return responseList;
    }


    @PostMapping("/save")
    @Operation(summary = "管理员保存更新模型")
    public ChatModelDetailResponse save(@RequestBody ChatModelSaveRequest chatModelSaveRequest) {
        ChatModelEntity chatModelEntity = new ChatModelEntity();
        chatModelEntity.setSortNum(chatModelService.getMaxSortNum() + 1);
        if (chatModelSaveRequest.getId() != null) {
            chatModelEntity = chatModelService.getById(chatModelSaveRequest.getId());
        }
        if (chatModelEntity == null) {
            throw new BadRequestException("模型不存在");
        }
        ApiKeyEntity apiKeyEntity = apiKeyService.getOne(new LambdaQueryWrapper<ApiKeyEntity>()
                .eq(ApiKeyEntity::getChannel, chatModelSaveRequest.getChannel())
                .eq(ApiKeyEntity::getEnabled, Boolean.TRUE)
                .last("limit 1"));
        if (apiKeyEntity == null) {
            throw new BadRequestException("渠道不存在或未启用");
        }
        chatModelEntity.setPlatform(apiKeyEntity.getPlatform());
        chatModelEntity.setChannel(chatModelSaveRequest.getChannel());
        chatModelEntity.setName(chatModelSaveRequest.getName());
        chatModelEntity.setValue(chatModelSaveRequest.getValue());
        chatModelEntity.setPower(chatModelSaveRequest.getPower());
        chatModelEntity.setEnabled(chatModelSaveRequest.isEnabled());
        chatModelEntity.setOpen(chatModelSaveRequest.isOpen());
        chatModelEntity.setDescription(chatModelSaveRequest.getDescription());
        chatModelEntity.setEnabledFunction(chatModelSaveRequest.getEnabledFunction());
        chatModelEntity.setMaxContext(chatModelSaveRequest.getMaxContext());
        chatModelEntity.setMaxTokens(chatModelSaveRequest.getMaxTokens());
        chatModelEntity.setTemperature(chatModelSaveRequest.getTemperature());
        chatModelService.saveOrUpdate(chatModelEntity);
        ChatModelDetailResponse response = BeanUtil.copyProperties(chatModelEntity, ChatModelDetailResponse.class, "createdAt", "updatedAt");
        response.setCreatedAt(chatModelEntity.getCreatedAt().getEpochSecond());
        response.setUpdatedAt(chatModelEntity.getUpdatedAt().getEpochSecond());
        return response;
    }

    @GetMapping("/remove")
    @Operation(summary = "管理员删除模型")
    public void remove(@RequestParam(value = "id") Long id) {
        chatModelService.removeById(id);
    }

    @PostMapping("/set")
    @Operation(summary = "管理员设置模型状态")
    public void set(@RequestBody FiledUpdateRequest request) {
        chatModelService.update(new UpdateWrapper<ChatModelEntity>()
                .set(request.getFiled(), Boolean.valueOf(request.getValue()))
                .eq("id", Long.valueOf(request.getId())));
    }

}
